package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wfyn
 * @date 2023/10/7
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;


    /**
     * 提交订单
     *
     * @param ordersSubmitDTO 订单数据传输对象
     * @return OrderSubmitVO 包含订单信息的数据传输对象
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 根据地址簿ID获取地址簿信息
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());

        // 如果地址簿信息为空
        if (addressBook == null) {
            // 抛出地址簿业务异常，提示地址簿不存在
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 获取当前用户的ID
        Long userId = BaseContext.getCurrentId();

        // 创建购物车对象
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();

        // 获取当前用户的购物车列表
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        // 如果购物车列表为空
        if (list == null || list.isEmpty()) {
            // 抛出购物车业务异常，提示购物车为空
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 创建订单对象
        Orders orders = new Orders();

        // 将订单数据传输对象的属性复制到订单对象中
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        orders.setUserId(userId);

        // 设置订单时间为当前时间
        orders.setOrderTime(LocalDateTime.now());

        // 设置支付状态为未支付
        orders.setPayStatus(Orders.UN_PAID);

        // 设置订单状态为待付款
        orders.setStatus(Orders.PENDING_PAYMENT);

        // 生成订单号，通常使用时间戳
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        // 设置订单的联系电话和收货人信息
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());

        // 设置订单的地址信息，包括省、市、区和详细地址
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        // 插入订单到数据库
        orderMapper.insert(orders);

        // 创建订单详情列表
        List<OrderDetail> orderDetailList = new ArrayList<>();

        // 遍历购物车中的商品，创建订单详情对象并添加到列表中
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();

            // 将购物车项的属性复制到订单详情对象中
            BeanUtils.copyProperties(cart, orderDetail);

            // 设置订单详情的订单ID
            orderDetail.setOrderId(orders.getId());

            // 将订单详情添加到列表中
            orderDetailList.add(orderDetail);
        }

        // 批量插入订单详情到数据库
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空当前用户的购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 创建订单提交响应对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //通过webSocket向客户端发送订单支付成功的消息
        HashMap<String, Object> map = new HashMap<>();

        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content","订单号"+ outTradeNo);

        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);

    }

    @Override
    public OrderVO orderDetail(String id) {

        OrderVO orderVO = new OrderVO();

        // 根据订单号查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        orderVO.setOrderDetailList(orderDetailList);


        return orderVO;
    }

    /**
     * 客户催单
     * @param id
     */
    public void reminder(String id) {

        // 根据订单号查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        HashMap<String, Object> map = new HashMap<>();

        map.put("type", 2);
        map.put("orderId", id);
        map.put("content","订单号"+ orders.getNumber());

        //向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 使用PageHelper分页插件设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 查询订单列表
        Page<OrderVO> orderList = orderMapper.pageList(ordersPageQueryDTO);

        // 如果订单列表不为空，则创建一个包含总记录数和订单列表的PageResult对象，否则返回null
        return orderList != null ? new PageResult(orderList.getTotal(), mapOrderListWithDetails(orderList)) : null;
    }



    /**
     * 再来一单
     * @param id
     */
    public void repetition(String id) {


        // 根据订单号查询订单
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(Long.valueOf(id));

        //放入购物车
        orderDetailList.forEach(orderDetail -> {

            ShoppingCart cart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail, cart);

            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());

            shoppingCartMapper.insert(cart);

        });


    }

    @Override
    public void cancel(String id) {
        // 根据订单号查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消订单");

        orderMapper.update(orders);
    }

    /**
     * 商家拒绝订单
     * @param ordersRejectionDTO
     */
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据订单号查询订单
        Orders orders = orderMapper.getById(String.valueOf(ordersRejectionDTO.getId()));
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.REFUNDED);

        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());

        orderMapper.update(orders);
    }

    @Override
    public OrderStatisticsVO statistics() {

        return orderMapper.statistics();
    }

    @Override
    public void complete(String id) {
        // 根据订单号查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        // 使用PageHelper分页插件设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 查询订单列表
        Page<OrderVO> orderList = orderMapper.pageList(ordersPageQueryDTO);

          // 如果订单列表不为空，则创建一个包含总记录数和订单列表的PageResult对象，否则返回null
        return orderList != null ? new PageResult(orderList.getTotal(), mapOrderListWithOrderDishes(orderList)) : null;

    }

    /**
     * 接单
     * @param id
     */
    public void confirm(Long id) {
        Orders orders = orderMapper.getById(String.valueOf(id));
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.CONFIRMED);
        orders.setEstimatedDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    /**
     * 派送
     * @param id
     */
    public void delivery(String id) {
        // 根据订单号查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     *
     * @param ordersCancelDTO
     */
    public void ordersCancelOrder(OrdersCancelDTO ordersCancelDTO) {
        // 根据订单号查询订单
        Orders orders = orderMapper.getById(String.valueOf(ordersCancelDTO.getId()));
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);


    }







    // 将订单列表与订单详情关联并返回
        private List<OrderVO> mapOrderListWithOrderDishes(Page<OrderVO> orderList) {
            return orderList.stream()
                    .map(order -> {
                        // 查询订单对应的订单详情列表
                        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());

                        // 构建orderDishes字符串，将订单详情列表中的name和dishflavor拼接起来
                        StringBuilder orderDishesBuilder = new StringBuilder();
                        for (OrderDetail detail : orderDetailList) {
                            if (orderDishesBuilder.length() > 0) {
                                orderDishesBuilder.append(", ");
                            }
                            orderDishesBuilder.append(detail.getName());

                            // 检查dishFlavor是否为空
                            if (detail.getDishFlavor() != null && !detail.getDishFlavor().isEmpty()) {
                                orderDishesBuilder.append(" (").append(detail.getDishFlavor()).append(")");
                            }
                        }

                        // 最终的orderDishes字符串
                        String orderDishes = orderDishesBuilder.toString();

                        // 设置orderDishes到订单对象的orderDishes字段中
                        order.setOrderDishes(orderDishes);

                        return order;
                    })
                    .collect(Collectors.toList());
        }

    // 将订单列表与订单详情关联并返回
    private List<OrderVO> mapOrderListWithDetails(Page<OrderVO> orderList) {
        return orderList.stream()
                .map(order -> {
                    // 创建一个新的OrderVO对象，并将订单信息拷贝到新对象中
                    OrderVO orderVO = new OrderVO();
                    BeanUtils.copyProperties(order, orderVO);

                    // 查询订单对应的订单详情列表
                    List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());

                    // 将订单详情列表设置到订单对象中
                    orderVO.setOrderDetailList(orderDetailList);

                    return orderVO;
                })
                .collect(Collectors.toList());
    }


}

